package io.github.talelin.latticy.filter;

import io.github.talelin.latticy.common.aop.BodyReaderHttpServletRequestWrapper;
import io.github.talelin.latticy.common.pojo.DynamicConfigEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @authoer:wulongbo
 * @createDate:2022/5/31
 * @description:
 */
@Slf4j
@WebFilter(filterName = "RequestWrapperFilter")
@Component
public class RequestWrapperFilter implements Filter {

    @Autowired
    private DynamicConfigEntity entity;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException
            , IOException {
        ServletRequest requestWrapper = null;
        boolean flag;
        if (request instanceof HttpServletRequest) {
            String currentUrl = ((HttpServletRequest) request).getServletPath();
            flag = entity.getUrls().contains(currentUrl);
            if (!flag) {
                requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
            }
        }
        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {

    }

}

